package com.wangshen.base.ui.mvp.base.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;


import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;

import com.wangshen.base.dialog.SampleDialog;
import com.wangshen.base.dialog.base.BaseDialog;
import com.wangshen.base.ui.mvp.base.presenter.BasePresenter;
import com.wangshen.base.ui.mvp.base.view.BaseView;
import com.wangshen.base.util.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @name Base
 * @class describe
 * @anthor 王文章
 * @time 2018/12/20 16:57
 * @change
 */
public abstract class BaseMvpActivity <P extends BasePresenter> extends BaseActivity implements BaseView, LifecycleOwner {
    protected P presenter;
    private LifecycleRegistry mRegistry;
    protected BaseDialog dialog;
    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter=getPresenter();
        presenter.attchView(this);
        getLifecycle().addObserver(presenter);
        dialog=getDialog();
    }

    @Override
    public void showLoadingDialog() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (dialog != null && !dialog.isShowing() && !isFinishing()){
                    dialog.show();
                }
            }
        });

    }

    @Override
    public void finishActivity() {
        finish();
    }

    @Override
    public void hideLoadingDialog() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (dialog != null && dialog.isShowing() && !isFinishing()){
                    dialog.dismiss();
                }
            }
        });
    }

    public BaseDialog getDialog() {
        return new SampleDialog(this);
    }

    @Override
    public Context getProviderContext() {
        return mContext;
    }

    public abstract P getPresenter();

    @Override
    public void startIntent(String key) {
        super.startIntent(key);
    }

    @Override
    public void startIntent(String key, Bundle bundle) {
        super.startIntent(key, bundle);
    }

    @Override
    public void showMessage(String msg) {
        ToastUtils.showToast(this,msg);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null){
            presenter.detachView();
        }
    }
    //手机号判断 true为通过验证
    public  boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        if (str == null) {
            return false;
        }
        if (str.length() != 11) {
            return false;
        }
        Pattern p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$");
        Matcher m = p.matcher(str);
        return m.matches();
    }

    public void downloadFile(String url) {
        final long startTime = System.currentTimeMillis();
        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                e.printStackTrace();
                Log.e("video", e.getMessage() + "");
                hideLoadingDialog();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = Environment.getExternalStorageDirectory().getAbsolutePath();
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
//                        listener.onDownloading(progress);
                        Log.e("video", progress + "");
                    }
                   runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showToast(BaseMvpActivity.this, "保存成功");
                            hideLoadingDialog();
                        }
                    });

                    fos.flush();

                } catch (Exception e) {
                    hideLoadingDialog();
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                        hideLoadingDialog();
                    }
                }
            }
        });
    }
}
